import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';

const ProtectedRoute = ({ children, requiredPermission }) => {
  const { user, loading, hasPermission } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    if (!loading && !user) {
      // 用户未登录，重定向到登录页
      navigate('/login');
    } else if (requiredPermission && !hasPermission(requiredPermission)) {
      // 用户没有所需权限，重定向到首页或无权限页面
      navigate('/unauthorized');
    }
  }, [user, loading, navigate, requiredPermission, hasPermission]);

  if (loading) {
    return <div>加载中...</div>;
  }

  if (!user) {
    return null;
  }

  if (requiredPermission && !hasPermission(requiredPermission)) {
    return (
      <div style={{ padding: 24, textAlign: 'center' }}>
        <h2>权限不足</h2>
        <p>您没有访问此页面的权限</p>
      </div>
    );
  }

  return children;
};

export default ProtectedRoute;
